package com.lovemanai.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name="upload", urlPatterns="/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		
		//获得请求参数
		String name = request.getParameter("name");
		out.println("name:" + name + "<br/>");
		//获得文件上传域
		Part part = request.getPart("file");
		
		//获得文件类型 
		out.println("文件类型：" + part.getContentType() + "<br/>");
		//获得文件大小
		out.println("文件大小：" + part.getSize() + "<br/>");
		
		//获得文件上传域的Header Name
		Collection<String> headNames = part.getHeaderNames();
		
		for (String headName : headNames) {
			out.println("Head Name ----> " + headName + "<br/>");
		}
		
		//获得原始文件名
		String fileInfo = part.getHeader("content-disposition");
		out.println(fileInfo);
		out.flush();
		//将文件写入服务器
		part.write(getServletContext().getRealPath("/uploadfile") + "IMG.jpg" );
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doGet(request, response);
		
	}
	
	
}